package org.numb.concurrency.chapter02;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class MyCallable implements Callable<Integer> {
    @Override
    public Integer call() throws Exception {
        int i = 0;
        while(i < 100) {
            System.out.println("Thread running: " + i++);
        }
        return i;
    }

    public static void main(String[] args) {
        // 创建callable对象，每一个callable对象可以看做一个任务
        MyCallable callable = new MyCallable();
        // 创建一个线程池
        ExecutorService threadPool = Executors.newFixedThreadPool(10);
        // Callable必须使用ExecutorService.submit来提交callable任务，返回值用Future对象去接收
        Future<Integer> result = threadPool.submit(callable);
        // get()方法获取线程返回值
        try {
            int i = (int) result.get();
            System.out.println(i);
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }
}
